#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) Huoty, All rights reserved
# Author: Huoty <sudohuoty@gmail.com>
# CreateTime: 2018-01-19 22:59:12

import os
import warnings
import yaml


# 邮件报告模板
email_template = """\
<style type="text/css">
    table {{
        width: 100%;
        border: 0px solid #e5e5e5;
    }}
    th,td {{
        padding: 8px 0px 4px 5px;
        text-align: center;
        border: 0px solid #e5e5e5;
    }}
    th {{
        font-size: 116%;
    }}
    tbody tr:nth-child(odd) {{
        background-color: #f2f2f2;
    }}
    tbody tr:nth-child(even) {{
        background-color: #fafafa;
    }}
    tbody tr:hover {{
        background-color: #e5e5e5;
    }}
</style>
<body>
    <pre>
        <strong>Marking strategy has been completed.</strong>

        <strong>Host:</strong> {host}
        <strong>User:</strong> {user}
        <strong>Python:</strong> {python}
        <strong>Time:</strong> {dt}

        <strong>Top 20:</strong> {top_ten}
        <strong>After 20:</strong> {after_ten}
    </pre>
</body>
"""

# 邮件发送配置，配置时会发送错误日志报告邮件，否则不发送
email = dict(
    host="",       # 发件邮箱 smtp 服务器
    addr="",       # 发件邮箱地址
    passwd="",     # 发件邮箱密码
    toaddrs=[]     # 收件人列表
)

# 日志相关配置
log_file_path = None
log_file_maxsize = 20 * 1024 * 1024
log_file_backups = 10

log_format = "[%(levelname)1.1s %(asctime)s %(name)s] %(message)s"
error_mail_format = """\
Logger Name:        %(name)s
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Host:               %(host)s
User:               %(user)s
Time:               %(asctime)s

Message:

%(message)s
"""


class Config(object):
    """Tronitor configration"""

    def __new__(cls, path=None):
        if not hasattr(cls, "_instance"):
            cls._instance = super(Config, cls).__new__(cls)
            cls._instance.initialize(path)
        return cls._instance

    def initialize(self, path=None):
        self._cfg_dct = globals()

        curr_path = os.path.dirname(os.path.realpath(__file__))
        config_paths = (
            os.path.join(curr_path, "../config.yml"),
            "/etc/tronitor_conf.yml",
            os.path.join(os.getenv("HOME"), "tronitor_conf.yml"),
            os.getenv("TRONITOR_CONFIG_PATH"),
            path
        )

        for config_path in config_paths:
            self._extract_config(config_path)

    def _extract_config(self, path):
        if not path or not os.path.exists(path):
            return

        with open(path) as f:
            self._cfg_dct.update(yaml.safe_load(f))

    def __getattr__(self, name):
        try:
            return self._cfg_dct[name]
        except KeyError:
            warnings.warn("No config '%s'" % name, Warning)
            return None


def load_config(path=None):
    return Config(path)
